import ProductAPI from '@/api/Product';
import {mapField, PaginationTable, SearchFields, SelectWithEmpty, useCall, usePaginationCommon} from '@/components';
import {MAIN_RISK_TYPE, PRODUCT_TYPE_INSURE} from '@/constants/options';
import {CompanySearchField} from '@/pages/components';
import {enumToOptions, pathJoin, pick} from '@/utils';
import request from '@/utils/request';
import {Button, message} from 'antd';
import React, {useRef, useState} from 'react';
import {Link} from 'react-router-dom';

const FIELDS = [
  [['searchFuzzy', 'business_code'], '业务编码'],
  [['searchFuzzy', 'product_code'], '险种编码'],
  [['searchFuzzy', 'product_name'], '险种名称'],
  [['t', 'companyName'], '保险公司', CompanySearchField],
  [['t', 'productType'], '主附险类型', SelectWithEmpty, {options: enumToOptions(PRODUCT_TYPE_INSURE)}],
].map(mapField);

function render(col, row) {
  const onClick = () => {
    sessionStorage.setItem('relationEditItem', JSON.stringify(row));
  };
  return (
    <Link onClick={onClick} to={pathJoin('addPage', pick(row, ['businessCode', 'productType'])[0])}>
      {col}
    </Link>
  );
}

const COLUMNS = [
  {key: 'index', title: '序号', format: 'order', width: 64},
  {dataIndex: 'businessCode', title: '业务编码', width: 160, sorter: true, render},
  {dataIndex: 'productCode', title: '险种编码', width: 160, sorter: true},
  {dataIndex: 'companyName', title: '保险公司', width: 110, ellipsis: true},
  {dataIndex: 'productName', title: '险种名称', minWidth: 100},
  {dataIndex: 'productType', title: '主附险类型', map: PRODUCT_TYPE_INSURE, width: 120},
  // { dataIndex: 'num0', title: '可附加', width: 80, align: 'center' },
  // { dataIndex: 'num1', title: '捆绑', width: 80, align: 'center' },
  // { dataIndex: 'num2', title: '互斥', width: 80, align: 'center' },
  // { dataIndex: 'num3', title: '被附加', width: 80, align: 'center' },
];

const download = (filename, file) => {
  let blob = new Blob([file], {type: 'sql/plain'});
  let url = window.URL.createObjectURL(blob);
  let a = document.createElement('a');
  a.href = url;
  a.download = filename + '.sql';
  a.click();
  window.URL.revokeObjectURL(url);
  a = null;
};

function DownloadBtn(props) {
  const { row } = props
  const [loading, setLoading] = useState(false)

  const onClick = useCall(async () => {
    setLoading(true)
    const { productCode }  = row
    try {
      const file = await request.get('/sql/exportSql', {hideMsg: true,dontThrow: true, params: { productCode }})
      console.log({ productCode, file })
      download(`export-${productCode}`, file)
    } catch (e) {
      message.error('导出失败', e.message)
    } finally {
      setLoading(false)
    }
  })

  return <Button size="small" type="link" onClick={onClick} loading={loading}>导出</Button>;
}

function ContactPage() {
  const {tableRef, searchData, onSearch, onSelect, selectedRef, reset} = usePaginationCommon();


  const actions = useRef({
    exportSql(row) {
      if (row.productType === MAIN_RISK_TYPE) return false;
      return <DownloadBtn row={row} />
    }
  }).current;

  return (
    <>
      <SearchFields fields={FIELDS} onSubmit={onSearch} onReset={onSearch}/>

      <PaginationTable ref={tableRef} service={ProductAPI.getList} serviceData={searchData} columns={COLUMNS} actions={actions} actionWidth={72}/>
    </>
  );
}

export default ContactPage;
